package com.mes.eventhandler;

import com.mes.data.EmesPBom;
import com.mes.data.EmesPBomItem;
import com.mes.plan.data.EmesPlanOrder;
import com.mes.plan.data.EmesPlanOrderBomItem;
import org.hibernate.Query;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.base.model.Property;
import org.openbravo.client.kernel.event.EntityDeleteEvent;
import org.openbravo.client.kernel.event.EntityNewEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;
import javax.enterprise.event.Observes;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EmesPlanOrderEventHandler extends EntityPersistenceEventObserver {
	private static Entity[] entities = { ModelProvider.getInstance().getEntity(EmesPlanOrder.ENTITY_NAME) };

	@Override
	protected Entity[] getObservedEntities() {
		return entities;
	}
	public void onUpdate(@Observes EntityUpdateEvent event) throws Throwable {
		if (!isValidEvent(event)) {
			return;
		}
		
		//获取产品ID
		EmesPlanOrder order = (EmesPlanOrder) event.getTargetInstance();
		
		if(!order.getStatus().equalsIgnoreCase("CREATE")){
			return;
		}
		
		Date sDate = order.getPlanedDateFrom();
		Date eDate = order.getPlanedDateTo();
		
		if(eDate.before(new Date())){
			String language = OBContext.getOBContext().getLanguage().getLanguage();
	        ConnectionProvider conn = new DalConnectionProvider(false);
	        throw new OBException(Utility.messageBD(conn, "计划结束时间早于当前时间，请仔细检查", language));
		}
		
		if(sDate != null){
			if(sDate.after(eDate)){
				String language = OBContext.getOBContext().getLanguage().getLanguage();
		        ConnectionProvider conn = new DalConnectionProvider(false);
		        throw new OBException(Utility.messageBD(conn, "计划开始时间晚于计划结束时间，请仔细检查", language));
			}
		}
		
		try {
			String product_id = order.getProduct().getId();
			String sqlDel = "delete Emesp_PlanOrder_BOMItem epi where epi.emesp_planorder_id = ?";
			
			Query query = OBDal.getInstance().getSession().createSQLQuery(sqlDel);
			query.setString(0, order.getId());
			query.executeUpdate();
			
			//定义计划订单的生产类型
			String type = "";
			//获取bom项
			List<EmesPBomItem> list = new ArrayList<EmesPBomItem>();
			//根据物料获取bom
			EmesPBom pbom = (EmesPBom) OBDal.getInstance().getSession().createQuery("from Emes_PBom ep where ep.product.id = ? and ep.default = true ").setString(0, product_id).uniqueResult();
			
			final Entity planOrderEntity = ModelProvider.getInstance().getEntity(EmesPlanOrder.ENTITY_NAME);
			final Property pBomProperty = planOrderEntity.getProperty(EmesPlanOrder.PROPERTY_EMESPBOM);
	       
			
			//如果bom为空，则是零部件计划
			if(pbom == null){
				//获取该产品下所有物料BOM项
				
				String sql = "SELECT * FROM emes_pbom_item epi START WITH epi.emes_pbom_item_id = " +
			     "  (select emes_pbom_item_id from emes_pbom_item t where t.m_product_id = ? "+
	             "  and ((select is_default from emes_pbom ep where ep.emes_pbom_id = t.emes_pbom_id) = 'Y')) " +
	             "  CONNECT BY PRIOR epi.emes_pbom_item_id = epi.parent_id ";
				
				list = OBDal.getInstance().getSession().createSQLQuery(sql).addEntity(EmesPBomItem.ENTITY_NAME).setString(0, product_id).list();
				event.setCurrentState(pBomProperty, list.get(0).getEmesPbom());
				type = "NONE";
			}else{
				list = pbom.getEmesPBomItemList();
				event.setCurrentState(pBomProperty,pbom);
				type = "BOM";
			}
			
			BigDecimal orderQty = null;
			
			if(type.equalsIgnoreCase("NONE")){
				for(EmesPBomItem o:list){
					if(o.getProduct().getId().equalsIgnoreCase(order.getProduct().getId())){
						orderQty = new BigDecimal(order.getQty()).divide(o.getItemQty());
					}else{
						continue;
					}
				}
			}else{
				orderQty = new BigDecimal(order.getQty());
			}
			for(EmesPBomItem o:list){
				if(o.isStopExpan()){
					EmesPlanOrderBomItem epob = new EmesPlanOrderBomItem();
					epob.setEmespPlanorder(order);
					epob.setProduct(o.getProduct());
					epob.setQty(o.getItemQty().multiply(orderQty).longValue());
					epob.setBOMIndex(o.getSeqno());
					OBDal.getInstance().save(epob);
				}
			}
			} catch (Exception e) {
				e.printStackTrace();
			}
		
	}
	
	//导入计划的时候保存bom项
	public void onSave(@Observes EntityNewEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
//		try {
			
		
		OBContext.setAdminMode();
        //获取产品ID
		EmesPlanOrder order = (EmesPlanOrder) event.getTargetInstance();
		String product_id = order.getProduct().getId();
		
		Date sDate = order.getPlanedDateFrom();
		Date eDate = order.getPlanedDateTo();
		
		if(eDate.before(new Date())){
			String language = OBContext.getOBContext().getLanguage().getLanguage();
	        ConnectionProvider conn = new DalConnectionProvider(false);
	        throw new OBException(Utility.messageBD(conn, "计划结束时间早于当前时间，请仔细检查", language));
		}
		
		if(sDate != null){
			if(sDate.after(eDate)){
				String language = OBContext.getOBContext().getLanguage().getLanguage();
		        ConnectionProvider conn = new DalConnectionProvider(false);
		        throw new OBException(Utility.messageBD(conn, "计划开始时间晚于计划结束时间，请仔细检查", language));
			}
		}
		
//		try {
		//定义计划订单的生产类型
		String type = "";
		//获取bom项
		List<EmesPBomItem> list = new ArrayList<EmesPBomItem>();
		//根据物料获取bom
		EmesPBom pbom = (EmesPBom) OBDal.getInstance().getSession().createQuery("from Emes_PBom ep where ep.product.id = ? and ep.default = true ").setString(0, product_id).uniqueResult();
		
		final Entity planOrderEntity = ModelProvider.getInstance().getEntity(EmesPlanOrder.ENTITY_NAME);
		final Property pBomProperty = planOrderEntity.getProperty(EmesPlanOrder.PROPERTY_EMESPBOM);
       
		
		//如果bom为空，则是零部件计划
		if(pbom == null){
			//获取该产品下所有物料BOM项
			
			String sql = "SELECT * FROM emes_pbom_item epi START WITH epi.emes_pbom_item_id = " +
					     "  (select emes_pbom_item_id from emes_pbom_item t where t.m_product_id = ? "+
			             "  and ((select is_default from emes_pbom ep where ep.emes_pbom_id = t.emes_pbom_id) = 'Y')) " +
			             "  CONNECT BY PRIOR epi.emes_pbom_item_id = epi.parent_id ";
			
			list = OBDal.getInstance().getSession().createSQLQuery(sql).addEntity(EmesPBomItem.ENTITY_NAME).setString(0, product_id).list();
			event.setCurrentState(pBomProperty, list.get(0).getEmesPbom());
			type = "NONE";
		}else{
			list = pbom.getEmesPBomItemList();
			event.setCurrentState(pBomProperty,pbom);
			type = "BOM";
		}
		
		BigDecimal orderQty = null;
		
		if(type.equalsIgnoreCase("NONE")){
			for(EmesPBomItem o:list){
				if(o.getProduct().getId().equalsIgnoreCase(order.getProduct().getId())){
					orderQty = new BigDecimal(order.getQty()).divide(o.getItemQty());
				}else{
					continue;
				}
			}
		}else{
			orderQty = new BigDecimal(order.getQty());
		}
		
		for(EmesPBomItem o:list){
			if(o.isStopExpan()){
				EmesPlanOrderBomItem epob = new EmesPlanOrderBomItem();
				epob.setEmespPlanorder(order);
				epob.setProduct(o.getProduct());
				epob.setQty(o.getItemQty().multiply(orderQty).longValue());
//				epob.setOrganization(o.getOrganization());
				epob.setBOMIndex(o.getSeqno());
				OBDal.getInstance().save(epob);
			}
		}
		
//		} catch (Exception e) {
//			e.printStackTrace();
//		}finally{
//			OBContext.restorePreviousMode();
//		}
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//		}
	}
	
	public void onDelete(@Observes
	EntityDeleteEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
	}
	
}
